package com.jay.nio.clazz;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;

//page 95, Fundamental+Networking+in+Java.pdf
public class ByteBufferView {
	public static void main(String[] args) {
		float[] floats = new float[] { (float) 1.1, (float) 2.2 };
		ByteBuffer byteBuffer = ByteBuffer.allocate(10);
		// 用Float View，减少操作次数，提高效率
		FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
		floatBuffer.put(floats);
		floatBuffer.flip();
		// 保证limit，position之类的同步
		Buffers.synchronize(floatBuffer, byteBuffer);
		// channel.write(byteBuffer);
	}
}

final class Buffers {
	private Buffers() {
	} // non-constructable

	/**
	 * Synchronize position and limit of <code>target</code> with those of its
	 * view buffer <code>view</code>, taking into account datatype item size
	 * differences.
	 * 
	 * @param view
	 *            source buffer, e.g. FloatBuffer
	 * @param target
	 *            the ByteBuffer underlying the view.
	 */
	public static void synchronize(final Buffer view, ByteBuffer target) {
		int factor = target.capacity() / view.capacity();
		target.limit(view.limit() * factor);
		target.position(view.position() * factor);
	}
}